package com.wzy.flowable.flow.Controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.ProcessEngine;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.repository.Deployment;
import org.flowable.engine.runtime.Execution;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: wzy
 * @Date: 2022/01/22/13:31
 * @Description:
 */
@RestController
@Slf4j
@Api(value = "flowable部署")
public class FlowController {

    @Autowired
    private ProcessEngine processEngine;
    @Autowired
    private RuntimeService runtimeService;

    /**
     * 部署流程定义
     */
    @ApiOperation(value = "部署")
    @GetMapping("/definition")
    public String deploymentFlowDefinition() {
        RepositoryService repositoryService = processEngine.getRepositoryService();
        Deployment deployment = repositoryService.createDeployment()
                .addClasspathResource("flowable/stu_level.bpmn20.xml")
                .name("请假流程部署-test")
                .deploy();
        return "部署成功";
    }

    /**
     * 启动
     */
    @GetMapping("/start/{processDefinitionKey}")
    public void startProcess(@PathVariable(value = "processDefinitionKey") String processDefinitionKey) {
        /*
         * @Date: 2021/10/17 23:40
         * Step 3: 启动流程，创建实例
         */
        //String processDefinitionKey = "请假";//流程定义的key,对应请假的流程图
        String businessKey = "schoolleave";//业务代码，根据自己的业务用
        Map<String, Object> variablesDefinition = new HashMap<>();//流程变量，可以自定义扩充
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processDefinitionKey, businessKey, variablesDefinition);
        log.info("启动成功:{}", processInstance.getId());

        /*
         * @Date: 2021/10/17 23:40
         * Step 4: 查询指定流程所有启动的实例列表
         * 列表，或 分页 删除
         */
        List<Execution> executions = runtimeService.createExecutionQuery().processDefinitionKey(processDefinitionKey).list();
        List<Execution> executionPages = runtimeService.createExecutionQuery().processDefinitionKey(processDefinitionKey).listPage(1, 30);
//        runtimeService.deleteProcessInstance(processInstanceId, deleteReason); //删除实例
    }


}
